package org.bapoint.bawirelessprogressusercenter.config;


import com.alibaba.nacos.api.naming.NamingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class NacosConnectionWaiter {

    private static final Logger log = LoggerFactory.getLogger(NacosConnectionWaiter.class);

    @Autowired(required = false)
    private NamingService namingService;

    @Bean
    public ApplicationRunner nacosWaiter() {
        return args -> {
            if (namingService == null) {
                log.warn("NamingService not found, skipping wait.");
                return;
            }

            int maxRetries = 15;
            long waitMillis = 2000L;

            for (int i = 1; i <= maxRetries; i++) {
                try {
                    namingService.getServicesOfServer(1, 10);
                    log.info("✅ Nacos Discovery client connected successfully. (Attempt {})", i);
                    return;
                } catch (Exception e) {
                    log.warn("🔁 Waiting for Nacos Discovery... retry {}/{} (Error: {})", i, maxRetries, e.getMessage());
                    if (i == maxRetries) {
                        log.error("❌ Nacos Discovery client failed to connect after {} attempts.", maxRetries);
                        throw new RuntimeException("Nacos Discovery connection failed", e);
                    }
                    Thread.sleep(waitMillis);
                }
            }
        };
    }
}